package com.qinhao.loveCrowdFunding.handler;

import com.qinhao.loveCrowdFunding.utils.AdminLoginUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class MyMessageHandler implements WebSocketHandler {
    private static final Logger log = Logger.getLogger(MyMessageHandler.class);
    // 用户key
    public static final String USER_KEY = "current_user";
    // 存储用户连接的WebSocket信息
    private static final Map<String, WebSocketSession> userMap;
    static {
        userMap = new ConcurrentHashMap<>(30);
    }
    // 建立WebSocket连接时调用该方法
    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        String userId = this.getUserId(webSocketSession);
        if (StringUtils.isNoneBlank(userId)) {
            userMap.put(userId, webSocketSession);
        }
    }
    // 客户端调用websocket.send时候，会调用该方法，进行数据通信
    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
        String msg = webSocketMessage.toString();
        String userId = this.getUserId(webSocketSession);
        log.info("该" + userId + "用户发送的消息是：" + msg);
    }
    // 传输过程出现异常的时候，调用该方法
    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        WebSocketMessage<String> message = new TextMessage("异常信息：" + throwable.getMessage());
    }
    // 关闭webSocket时调用该方法
    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        String userId = this.getUserId(webSocketSession);
        if (StringUtils.isNoneBlank(userId)) {
            userMap.remove(userId);
            log.info("该" + userId + "用户已经成功关闭");
            AdminLoginUtil.getHashSet().remove("admin" + userId);
        } else {
            log.info("关闭时，获取用户id为空");
        }
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
    // 发送信息给指定的用户
    public void sendMessageToUser(String userId, String contents) {
        WebSocketSession session = userMap.get(userId);
        System.out.println(userId);
        if (session != null && session.isOpen()) {
            try {
                TextMessage message = new TextMessage(contents);
                log.info(message);
                session.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    // 发送信息给所有用户
    public void sendMessageToAllUsers(String contents) {
        Set<String> userIds = userMap.keySet();
        for (String userId : userIds) {
            this.sendMessageToUser(userId, contents);
        }
    }
    // 获取用户id
    private String getUserId(WebSocketSession session) {
        try {
            String userId = (String)session.getAttributes().get(USER_KEY);
            return userId;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Map<String, WebSocketSession> getUserMap() {
        return userMap;
    }
}
